
package com.hulk.ratel.common.security;

import com.hulk.ratel.common.constant.enums.BussErrCode;
import com.hulk.ratel.common.exception.SecurityRteException;
import lombok.extern.slf4j.Slf4j;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author cmt
 * @version Create on:  2017年4月28日 上午11:32:07
 *          Class description
 * @E-mail:29572320@qq.com
 */

@Slf4j
public class ProvideSecurityWarper {

    /**
     * 用platformPriKey解密encryptKey
     *
     * @param cipherB64PartnerAESkey
     * @param platformPrivateKey
     * @return
     */
    public static String getPartnerAESKeyByPlatformPrivateKey(String cipherB64PartnerAESkey, PrivateKey platformPrivateKey) {

        String partnerAESKey = null;
        try {
            byte[] cipherPartnerAESkeyBytes = B64.decode(cipherB64PartnerAESkey);
            partnerAESKey = RSA.privateKeyDecrypt(cipherPartnerAESkeyBytes, platformPrivateKey);
        } catch (Exception e) {
            throw new SecurityRteException("", BussErrCode.E_100011.getErrCode(), BussErrCode.E_100011.getErrDesc());
        }
        return partnerAESKey;

    }


    /**
     * 用partnerAESKey解密encryptData
     *
     * @param cipherB64PlainText
     * @param partnerAESKey
     * @return
     */
    public static String getPlainTextByAESKey(String cipherB64PlainText, String partnerAESKey) {
        String plainText = null;
        try {
            byte[] cipherPlainBytes = B64.decode(cipherB64PlainText);
            plainText = AES.decode(cipherPlainBytes, partnerAESKey);
        } catch (Exception e) {
            log.error("partnerAESKey解密encryptData异常：{}", e);
            throw new SecurityRteException("", BussErrCode.E_100012.getErrCode(), BussErrCode.E_100012.getErrDesc());
        }
        return plainText;

    }

    /**
     * 用partnerPubKey验证签名
     *
     * @param plainText
     * @param signB64PlainText
     * @param partnerPublicKey
     * @return
     */
    public static boolean checkSignB64PlainTextByPartnerPublicKey(String plainText, String signB64PlainText, PublicKey partnerPublicKey) {
        //byte [] cipherPlainBytes =  Base64.decode(cipherB64PlainText);
        boolean flag = false;
        try {
            byte[] signPlainBytes = B64.decode(signB64PlainText);
            flag = RSA.verifyPublicKeyDigitalSign(plainText, signPlainBytes, partnerPublicKey);
        } catch (Exception e) {
            throw new SecurityRteException("", BussErrCode.E_100008.getErrCode(), BussErrCode.E_100008.getErrDesc());
        }
        return flag;

    }


}
